// pages/pk/matching/matching.js
var questions//所有题目的合集
var roomid//房间号
var nowPlayer//当前玩家
var daojishi;//声明一个倒计时的变量用于控制选项的出现
var newList=0;//题目进度
var totalScore=0//总分
const db = wx.cloud.database();
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIBind:true,
    list:0,//题目的顺序，对应数组的下标
    question:'',//单个题目对象
    questions:[],//所有题目的合集
    newPlayerName:'',
    addPlayerName:'',
    newPlayerAvatarUrl:'',
    addPlayerAvatarUrl:'',
    newTotalScore:0,
    addTotalScore:0,
    countDown:15*1000,//计时器2初试时间
    timeData:15,//中间倒计时
    circleValue:100,//默认倒计时进度条值
    gradientColor: {//倒计时进度条颜色渐变
      '0%':'#1989fa',
      '100%':'#ff3333',
    },
    hidden:false,//四个选项的显示与否，暂时废弃改用动画
    bga:'',//选项A的背景色
    bgb:'',//选项B的背景色
    bgc:'',//选项C的背景色
    bgd:'',//选项D的背景色
    showRightOrWrong:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],//显示答完题的正误，分别对应两个玩家四个选项的16个图标，用透明度控制显示
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    newList=0;//重置题目进度
    totalScore=0//总分
    var that=this
    console.log(options)
    roomid=options._id
    nowPlayer=options.player
    //获取openid，测试用
    // wx.cloud.callFunction({
    //   name: 'getopenid',
    //   complete: res => {
    //     console.log(res.result.openid)
    //     //查询个人储存进度信息
    //     var openid=res.result.openid
    //     if(openid=='oCjgw5XTbm6iuwIY7icelNG0b2UU'){
    //       nowPlayer='newPlayer'
    //     }else{
    //       nowPlayer='addPlayer'
    //     }
    //   }
    // });
    // nowPlayer='addPlayer'
    //roomid='1631983789583'
    //获取总共的10道题目
    db.collection('pkroom').doc(roomid).get().then(res => {
      let results=res.data
      questions=[results.Q1,results.Q2,results.Q3,results.Q4,results.Q5,results.Q6,results.Q7,results.Q8,results.Q9,results.Q10,]
      this.setData({
        questions:questions,
        question:questions[newList]
      })
      console.log(questions)
    })
    //获取房主信息
    db.collection('ddata').doc(options._openid).get().then(res => {//options._openid
      this.setData({
        newPlayerName:res.data.userInfo.nickName,
        newPlayerAvatarUrl:res.data.userInfo.avatarUrl,
      })
    })
    //获取玩家2信息
    db.collection('ddata').doc(options._openidAdd).get().then(res => {//options._openidAdd
      this.setData({
        addPlayerName:res.data.userInfo.nickName,
        addPlayerAvatarUrl:res.data.userInfo.avatarUrl,
      })
    })
    setTimeout(function(){
      that.setData({
        // hidden:false,
        show:true
      });
      that.countStart()
    },5000)
  },
  //触发、暂停和重置计时器的函数
  countStart:function(){
    const countDown = this.selectComponent('.control-count-down');//使用前必须定义组件的class为.control-count-down（与wxml的class名一致就行）
    countDown.start();
  },
  countPause:function() {
    const countDown = this.selectComponent('.control-count-down');
    console.log('暂停计时')
    countDown.pause();
  },
  countReset:function() {
    const countDown = this.selectComponent('.control-count-down');
    countDown.reset();
  },
  //监听倒计时数字变化赋值给中间的数字和进度条
  onCountChange(e) {
    let circleValue=Math.ceil(e.detail.seconds*100/15)
    console.log(e.detail.seconds)
    this.setData({
      timeData: e.detail.seconds,
      circleValue:circleValue
    });
    if(e.detail.seconds === 0 && e.detail.milliseconds==0){
      console.log('答题时间到')
    }
  },
  //倒计时结束时判定函数
  onfinished:function(){
    if(this.data.bga==''&&this.data.bgb==''&&this.data.bgc==''&&this.data.bgd==''){
      this.selectA()
    }
    //this.nextQuestion()
  },
  //将房主的选择上传到云端并对玩家2进行监听
  UploadSelection:function(selection,time,score,totalScore){
    var rightA//设置变量留着下边显示正确答案用
    let that=this
    console.log('房主的选择是:',selection,'剩余时间为',time,'秒','本题得分为',score,'总分为',totalScore)
    //设置四个变量更新数据库对应的10道不同题目
    let list=newList+1
    let newPlayerA='Q'+list+'.newPlayerA'
    let newTime='Q'+list+'.newTime'
    let newScore='Q'+list+'.newScore'
    db.collection('pkroom').doc(roomid).update({
      data: {
        [newPlayerA]:selection,//key值为变量时需要用中括号
        [newTime]:time,
        [newScore]:score,
        newPlayerAnswered:true,
        newTotalScore:totalScore
      },
    }).then(res => {
      console.log('开始查询对手（玩家2）数据')
      //获取玩家2答题信息
      var nowQuestion='Q'+list//获取当前是第几题
      db.collection('pkroom').doc(roomid).get().then(res => {
        console.log(res.data.addPlayerAnswered)
        if(res.data.addPlayerAnswered){
          this.data.showRightOrWrong[res.data[nowQuestion].addPlayerA[2]]=1//将玩家2的对错符号显示出来
          this.setData({
            [res.data[nowQuestion].addPlayerA[0]]:res.data[nowQuestion].addPlayerA[1],//将玩家2的选择内容及背景显示出来
            showRightOrWrong:this.data.showRightOrWrong,
            addTotalScore:res.data.addTotalScore
          })
          rightA=res.data[nowQuestion].rightA//赋值变量留着下边显示正确答案用
          this.showRightAnswer(rightA)
          //下一题,先重置数据库中的部分参数，再调用下一题
          setTimeout(function(){
            that.resetAnswered()
          },2000)
        }
        else{
          //监听玩家2更新数据
          this.listenAddPlayer = db.collection('pkroom')
          .where({
            _id: roomid
          })
          .watch({
            onChange: snapshot => {
              // const docChange = snapshot.docChanges[0];
              const doc = snapshot.docs[0];
              console.log('监听玩家2回答', snapshot);
              if (doc.addPlayerAnswered === true) {
                console.log('监听到玩家2已回答完毕');
                //将回答内容并显示在页面内
                console.log(doc[nowQuestion])
                this.data.showRightOrWrong[doc[nowQuestion].addPlayerA[2]]=1//将玩家2的对错符号显示出来
                this.setData({
                  [doc[nowQuestion].addPlayerA[0]]:doc[nowQuestion].addPlayerA[1],//将玩家2的选择内容及背景显示出来
                  showRightOrWrong:this.data.showRightOrWrong,
                  addTotalScore:doc.addTotalScore
                })
                this.listenAddPlayer.close();
                rightA=doc[nowQuestion].rightA//赋值变量留着下边显示正确答案用
                this.showRightAnswer(rightA)
                //下一题,先重置数据库中的部分参数，再调用下一题
                setTimeout(function(){
                  console.log('下一题')
                  that.resetAnswered()
                },2000)
              }
            },
            onError: error => {
                console.log(error);
            }
          })
        }
      })
    })
  },
  //将玩家2的选择上传到云端并对房主进行监听(通过云函数)
  UploadSelection2:function(selection,time,score){
    let that=this
    console.log('玩家2的选择是:',selection,'剩余时间为',time,'秒','本题得分为',score,'分')
    //设置四个变量更新数据库对应的10道不同题目
    let list=newList+1
    let addPlayerA='Q'+list+'.addPlayerA'
    let addTime='Q'+list+'.addTime'
    let addScore='Q'+list+'.addScore'
    var rightA
    console.log(totalScore)
    wx.cloud.callFunction({
      name: 'updateAddPlayer',
      data: {
        collection:'pkroom',
        _id: roomid,
        addPlayerA: addPlayerA,
        addTime: addTime,
        addScore: addScore,
        selection: selection,
        time: time,
        score: score,
        totalScore:totalScore
      },
    })
    .then(res => {
      console.log('云函数调用成功',res.result) 
      console.log('开始查询对手（房主）数据')
      var nowQuestion='Q'+list//获取当前是第几题
      //获取房主答题信息
      db.collection('pkroom').doc(roomid).get().then(res => {
        console.log(res.data.newPlayerAnswered)
        if(res.data.newPlayerAnswered){
          this.data.showRightOrWrong[res.data[nowQuestion].newPlayerA[2]]=1//将玩家2的对错符号显示出来
          this.setData({
            [res.data[nowQuestion].newPlayerA[0]]:res.data[nowQuestion].newPlayerA[1],//将玩家2的选择内容及背景显示出来
            showRightOrWrong:this.data.showRightOrWrong,
            newTotalScore:res.data.newTotalScore
          })
          rightA=res.data[nowQuestion].rightA//赋值变量留着下边显示正确答案用
          this.showRightAnswer(rightA)
          //下一题,先重置数据库中的部分参数，再调用下一题
          setTimeout(function(){
            console.log('下一题')
            that.resetAnswered()
          },3000)
        }
        else{
          //监听玩家2更新数据
          this.listenNewPlayer = db.collection('pkroom')
          .where({
            _id: roomid
          })
          .watch({
            onChange: snapshot => {
              // const docChange = snapshot.docChanges[0];
              const doc = snapshot.docs[0];
              console.log('监听房主的回答', snapshot);
              if (doc.newPlayerAnswered === true) {
                console.log('监听到房主已回答完毕');
                //将回答内容并显示在页面内
                console.log(doc[nowQuestion])
                this.data.showRightOrWrong[doc[nowQuestion].newPlayerA[2]]=1//将玩家2的对错符号显示出来
                this.setData({
                  [doc[nowQuestion].newPlayerA[0]]:doc[nowQuestion].newPlayerA[1],//将玩家2的选择内容及背景显示出来
                  showRightOrWrong:this.data.showRightOrWrong,
                  newTotalScore:doc.newTotalScore
                })
                this.listenNewPlayer.close();
                rightA=doc[nowQuestion].rightA//赋值变量留着下边显示正确答案用
                this.showRightAnswer(rightA)
                //下一题,先重置数据库中的部分参数，再调用下一题
                setTimeout(function(){
                  console.log('下一题')
                  that.resetAnswered()
                },2000)
              }
            },
            onError: error => {
                console.log(error);
            }
          })
        }
      })
    })
    .catch(console.error)
  },
  //修改数据库中的两个answered为false
  resetAnswered:function(){
    db.collection('pkroom').doc(roomid).update({
      data: {
        newPlayerAnswered:false,
        addPlayerAnswered:false
      },
    }).then(res => {
      console.log('下一题')
      this.nextQuestion()
      })
  },
  //显示正确答案
  showRightAnswer:function(rightA){
    if(rightA=='A'){
      this.setData({
        bga:'#00e2bc'
      })
    }else if(rightA=='B'){
      this.setData({
        bgb:'#00e2bc'
      })
    }else if(rightA=='C'){
      this.setData({
        bgc:'#00e2bc'
      })
    }else if(rightA=='D'){
      this.setData({
        bgd:'#00e2bc'
      })
    }
  },
  //选择A选项的函数
  selectA:function(){
    let selection=[]
    let time=this.data.timeData
    let score
    let rightA=this.data.question.rightA
    if(rightA=='A'){
      this.setData({
        bga:'#00e2bc',//正确的颜色
        canIBind:false,//点击一次后禁止再点击
      })
      if(time>10){score=10}else{score=time*1}
      totalScore=totalScore+score
      if(nowPlayer=='newPlayer'){
        this.setData({newTotalScore:totalScore})//赋值总分到页面也可以把showRightOrWrong的赋值一块写进来
        this.data.showRightOrWrong[0]=1,
        selection=['bga',this.data.bga,0]//将选项、正误(选项背景色)、对错号图标位置都放到数组中方便对手查询
      }else{
        this.setData({addTotalScore:totalScore})
        this.data.showRightOrWrong[2]=1,
        selection=['bga',this.data.bga,2]
      }
      //wx:if只有用setData才能生效
      this.setData({
        showRightOrWrong:this.data.showRightOrWrong,
      })
    }else{
      this.setData({
        bga:'#ff7167',//错误的颜色
        canIBind:false,//点击一次后禁止再点击
      })
      score=0
      totalScore=totalScore+score
      if(nowPlayer=='newPlayer'){
        this.data.showRightOrWrong[1]=1
        selection=['bga',this.data.bga,1]
      }else{
        this.data.showRightOrWrong[3]=1
        selection=['bga',this.data.bga,3]
      }
      this.setData({
        showRightOrWrong:this.data.showRightOrWrong
      })
    }
    if(nowPlayer=='newPlayer'){
      this.UploadSelection(selection,time,score,totalScore)//将房主的答题数据上传到数据库
    }else{
      this.UploadSelection2(selection,time,score,totalScore)//将玩家2的答题数据上传到数据库
    }
  },
  //选择B选项的函数
  selectB:function(){
    let selection='B'
    let time=this.data.timeData
    let score
    let rightA=this.data.question.rightA
    if(rightA=='B'){
      this.setData({
        bgb:'#00e2bc',//正确的颜色
        canIBind:false,//点击一次后禁止再点击
      })
      if(time>10){score=10}else{score=time*1}
      totalScore=totalScore+score
      if(nowPlayer=='newPlayer'){
        this.setData({newTotalScore:totalScore})
        this.data.showRightOrWrong[4]=1
        selection=['bgb',this.data.bgb,4]
      }else{
        this.setData({addTotalScore:totalScore})
        this.data.showRightOrWrong[6]=1
        selection=['bgb',this.data.bgb,6]
      }
      this.setData({
        showRightOrWrong:this.data.showRightOrWrong
      })
    }else{
      this.setData({
        bgb:'#ff7167',//错误的颜色
        canIBind:false,//点击一次后禁止再点击
      })
      score=0
      totalScore=totalScore+score
      if(nowPlayer=='newPlayer'){
        this.data.showRightOrWrong[5]=1
        selection=['bgb',this.data.bgb,5]
      }else{
        this.data.showRightOrWrong[7]=1
        selection=['bgb',this.data.bgb,7]
      }
      this.setData({
        showRightOrWrong:this.data.showRightOrWrong
      })
    }
    console.log(totalScore)
    if(nowPlayer=='newPlayer'){
      this.UploadSelection(selection,time,score,totalScore)//将房主的答题数据上传到数据库
    }else{
      this.UploadSelection2(selection,time,score,totalScore)//将玩家2的答题数据上传到数据库
    }
  },
  //选择C选项的函数
  selectC:function(){
    let selection='C'
    let time=this.data.timeData
    let score
    let rightA=this.data.question.rightA
    if(rightA=='C'){
      this.setData({
        bgc:'#00e2bc',//正确的颜色
        canIBind:false,
      })
      if(time>10){score=10}else{score=time*1}
      totalScore=totalScore+score
      if(nowPlayer=='newPlayer'){
        this.setData({newTotalScore:totalScore})
        this.data.showRightOrWrong[8]=1
        selection=['bgc',this.data.bgc,8]
      }else{
        this.setData({addTotalScore:totalScore})
        this.data.showRightOrWrong[10]=1
        selection=['bgc',this.data.bgc,10]
      }
      this.setData({
        showRightOrWrong:this.data.showRightOrWrong
      })
    }else{
      this.setData({
        bgc:'#ff7167',//错误的颜色
        canIBind:false,
      })
      score=0
      totalScore=totalScore+score
      if(nowPlayer=='newPlayer'){
        this.data.showRightOrWrong[9]=1
        selection=['bgc',this.data.bgc,9]
      }else{
        this.data.showRightOrWrong[11]=1
        selection=['bgc',this.data.bgc,11]
      }
      this.setData({
        showRightOrWrong:this.data.showRightOrWrong
      })
    }
    if(nowPlayer=='newPlayer'){
      this.UploadSelection(selection,time,score,totalScore)//将房主的答题数据上传到数据库
    }else{
      this.UploadSelection2(selection,time,score,totalScore)//将玩家2的答题数据上传到数据库
    }
  },
  //选择D选项的函数
  selectD:function(){
    let selection='C'
    let time=this.data.timeData
    let score
    let rightA=this.data.question.rightA
    if(rightA=='D'){
      this.setData({
        bgd:'#00e2bc',//正确的颜色
        canIBind:false,//点击一次后禁止再点击
      })
      if(time>10){score=10}else{score=time*1}
      totalScore=totalScore+score
      if(nowPlayer=='newPlayer'){
        this.setData({newTotalScore:totalScore})
        this.data.showRightOrWrong[12]=1
        selection=['bgd',this.data.bgd,12]
      }else{
        this.setData({addTotalScore:totalScore})
        this.data.showRightOrWrong[14]=1
        selection=['bgd',this.data.bgd,14]
      }
      this.setData({
        showRightOrWrong:this.data.showRightOrWrong
      })
    }else{
      this.setData({
        bgd:'#ff7167',//错误的颜色
        canIBind:false,//点击一次后禁止再点击
      })
      score=0
      totalScore=totalScore+score
      if(nowPlayer=='newPlayer'){
        this.data.showRightOrWrong[13]=1
        selection=['bgd',this.data.bgd,13]
      }else{
        this.data.showRightOrWrong[15]=1
        selection=['bgd',this.data.bgd,15]
      }
      this.setData({
        showRightOrWrong:this.data.showRightOrWrong
      })
    }
    if(nowPlayer=='newPlayer'){
      this.UploadSelection(selection,time,score,totalScore)//将房主的答题数据上传到数据库
    }else{
      this.UploadSelection2(selection,time,score,totalScore)//将玩家2的答题数据上传到数据库
    }
  },
  //切换到下一题
  nextQuestion:function(){
    var that=this
    newList=newList+1
    if(newList>9){
      wx.redirectTo({
        url: '../result/result?_id='+roomid+'&nowPlayer='+nowPlayer,
      })
    }
    this.setData({
      show:false,//控制四个选项出现的动画
      canIBind:true,//防止连击或者再点击其他选题
      question:questions[newList],
      countDown:15*1000,//计时器2初试时间
      timeData:15,//中间倒计时
      circleValue:100,//默认倒计时进度条值
      hidden:false,//四个选项的显示与否,暂时废弃改用动画
      bga:'',//选项A的背景色
      bgb:'',//选项B的背景色
      bgc:'',//选项C的背景色
      bgd:'',//选项D的背景色
      showRightOrWrong:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],//显示答完题的正误，分别对应两个玩家四个选项的16个图标，用透明度控制显示
    })
    that.countReset()
    setTimeout(function(){
      that.setData({
        hidden:false,
        show:true
      });
      that.countStart()
    },5000)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})